package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author : Rookie
 * @description : 最后一层左下角的值  即求最后一行第一个元素的值
 * @date : 2023/10/23
 */
public class LeftCornerVal {

    public static void main(String[] args) {
        int[] input = {3, 9, 20, -1, -1, 15, 7};
        TreeNode root = BinaryTreeUtil.buildTree(input);
        int res = iterativeImpl(root);
        System.out.println(res);
    }

    private static int iterativeImpl(TreeNode node) {
        if (node == null) {
            return -1;
        }
        int result = -1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);

        while (!queue.isEmpty()) {
            // 当前层的元素个数
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                if (curr == null) {
                    return result;
                }
                if (i == 0) {
                    result = curr.element;
                }
                if (curr.left != null) {
                    queue.offer(curr.left);
                }
                if (curr.right != null) {
                    queue.offer(curr.right);
                }
            }
        }
        return result;
    }
}
